// pages/bookRead/chapter/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    title: "",
    cover: "",
    order: 0,

    headerHeight: "160rpx",
    footerHeight: "160rpx",

    _id: "",
    chapterArr: "",
    chapterListData: "",

    chapterListWidth: "-80%",
    prevChapterColor: "#fff",
    nextChapterColor: "#fff",

    nextTime: 0,
    scrollTop: 0,

    chapterSize: 28,
    textColor: "rgba(0,0,0,0.8)",
    textBgcolor: "rgba(0,0,0,.1)",
    textStyle: [{
      textColor: "rgba(0,0,0,1)",
      textBgcolor: "rgba(255,255,255,1)",
    }, {
      textColor: "rgba(255,255,255,1)",
      textBgcolor: "rgba(0, 0, 0, 1)",
    }, {
      textColor: "rgba(0,0,0,0.8)",
      textBgcolor: "rgba(0,0,0,.3)",
    }, {
      textColor: "rgba(0,0,0,0.8)",
      textBgcolor: "rgba(0,0,0,.1)",
    }],


    xNum: 0,
    _xNum: 0

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.save_Id(options); // 将传来的id保存在data内。将书名保存在
    this.getBookIntroData(this.data._id)
  },

  createStyleNumber() {
    if (wx.getStorageSync("styleNumber")) {
      let number = wx.getStorageSync("styleNumber");
      this.setData({
        textColor: this.data.textStyle[number - 1].textColor,
        textBgcolor: this.data.textStyle[number - 1].textBgcolor
      })
    } else {
      wx.setStorage({
        key: 'styleNumber',
        data: 1
      })
    }
  },

  setTimeHeader() {
    let that = this;
    setTimeout(function() {
      that.setData({
        headerHeight: "80rpx"
      })
    }, 3000)
  },


  save_Id(_id) {
    this.setData({
      _id: encodeURIComponent(_id._id),
      title: _id.title,
      cover: _id.cover,
      order: _id.order
    })
  },

  getBookIntroData(_id) {
    let that = this;
    wx.request({
      url: `https://api.zhuishushenqi.com/atoc/${_id}?view=chapters`,
      success: res => {
        let newChapters = res.data.chapters.map(val => {
          let newObject = {
            link: val.link,
            title: val.title,
            isVip: val.isVip,
            order: val.order
          };
          return newObject;
        })
        let num = res.data.updated.indexOf("T");
        res.data.updated = res.data.updated.slice(0, num);
        res.data.chapters = newChapters;
        that.setData({
          chapterListData: res.data
        })


        let src = that.data.chapterListData.chapters[this.data.order - 1].link; // 获得第一章节的link
        // 获得初始数据
        this.getBookChapterDataFun(src, this.data.order - 1)
      }
    })
  },



  getBookChapterData(addsrc, nums) { // 通过传入的link获得章节数据
    let that = this;
    let src = encodeURIComponent(addsrc);
    return new Promise(function(resolve, reject) {
      wx.request({
        url: `https://chapter2.zhuishushenqi.com/chapter/${src}`, 
        success: res => {
          if (!res.data.chapter.order) {
            res.data.chapter.order = parseInt(nums) + 1;
          }
          if (!res.data.chapter.updated) {
            res.data.chapter.updated = "暂无数据"
          } else {
            let num = res.data.chapter.updated.indexOf("T");
            res.data.chapter.updated = res.data.chapter.updated.slice(0, num);
          }
          // that.setData({
          //   chapterArr: res.data.chapter
          // })
          resolve(res.data.chapter)
        }
      })
    })
  },

  changeHeaderHeight() {
    if (this.data.headerHeight === "80rpx") {
      this.setData({
        headerHeight: "160rpx"
      })
    } else {
      this.setData({
        headerHeight: "80rpx"
      })
    }

  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.createStyleNumber() // 初始化StyleNumber数据

    this.setTimeHeader();
    wx.setStorage({
      key: 'nextData',
      data: ''
    })
    this.data.nextTime = setTimeout(this.setTimeStorage, 10000)
  },


  setTimeStorage() {
    if (this.data.nextChapterColor === "#333") {
      return
    } else {
      if (this.data.chapterArr && this.data.chapterListData) {
        let addsrc = this.data.chapterArr.order
        this.getBookChapterData(this.data.chapterListData.chapters[addsrc].link, addsrc).then(res => {
          wx.setStorage({
            key: 'nextData',
            data: res
          })
        }).catch(err => {
          console.log(err)
        })
      }
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    clearTimeout(this.data.nextTime);

    this.saveStorageJl();
  },

  saveStorageJl() {
    let storageArr = wx.getStorageSync("jl");
    if (storageArr.length > 1000) {
      storageArr = storageArr.slice(0, 800)
    }
    let jl = {
      _id: this.data._id,
      title: this.data.title,
      cover: this.data.cover,
      order: this.data.chapterArr.order,
      chapterTitle: this.data.chapterArr.title,
      name: this.data.chapterListData.name
    }
    storageArr.unshift(jl)
    // arr.sort(function(v1, v2) {
    //   return v2.order - v1.order;
    // });
    let arr = [];
    storageArr.forEach(val => {
      let flog = true;
      if (arr.length === 0) {
        arr.push(val);
        return;
      } else {
        for (let i = 0; i < arr.length; i++) {
          if (arr[i]._id === val._id) {
            flog = false;
          }
        }
      }
      if (flog) {
        arr.push(val);
      }
    })
    wx.setStorage({
      key: 'jl',
      data: arr
    })
    // console.log(wx.getStorageSync("jl"))
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },


  toggleLink(e) { // 跳转章节
    let val = e.detail.split("-");
    this.getBookChapterDataFun(val[0], parseInt(val[1]))
    // this.toggleAll()

    clearTimeout(this.data.nextTime);
    wx.setStorage({
      key: 'nextData',
      data: ''
    })

    this.setData({
      chapterListWidth: "-80%"
    })
    this.data.nextTime = setTimeout(this.setTimeStorage, 10000)
  },

  toggleAll() {
    if (this.data.footerHeight === 0) {
      this.setData({
        headerHeight: "80rpx",
        footerHeight: "160rpx"
      })
    } else {
      this.setData({
        headerHeight: 0,
        footerHeight: 0
      })
    }
  },
  // 点击显示隐藏章节列表
  // toggleChaptersList() {
  //   if (this.data.chapterListWidth === "-100%") {
  //     this.setData({
  //       chapterListWidth: "0"
  //     })
  //   } else {
  //     this.setData({
  //       chapterListWidth: "-100%"
  //     })
  //   }
  // },

  // 跳转上一章
  prevChapter() {
    clearTimeout(this.data.nextTime);
    wx.setStorage({
      key: 'nextData',
      data: ''
    })
    this.data.nextTime = setTimeout(this.setTimeStorage, 10000)
    if (this.data.prevChapterColor === "#333") {
      return
    } else {
      if (this.data.chapterArr && this.data.chapterListData) {
        let addsrc = this.data.chapterArr.order
        this.getBookChapterDataFun(this.data.chapterListData.chapters[addsrc - 2].link, addsrc - 2)
      } else {
        return
      }

    }
  },

  // 跳转下一章
  nextChapter() {
    this.setData({
      scrollTop: 0
    })
    clearTimeout(this.data.nextTime);
    if (this.data.nextChapterColor === "#333") {
      return
    } else {
      let nextData = wx.getStorageSync("nextData");
      if (nextData) {
        this.stopEvent(nextData)
        this.setData({
          chapterArr: nextData
        })
        wx.setStorage({
          key: 'nextData',
          data: ''
        })
      } else {
        if (this.data.chapterArr && this.data.chapterListData) {
          let addsrc = this.data.chapterArr.order
          this.getBookChapterDataFun(this.data.chapterListData.chapters[addsrc].link, addsrc)
        } else {
          return
        }

        // 因为有的源缺少older值，所以用length代替
      }

      this.data.nextTime = setTimeout(this.setTimeStorage, 10000)
    }
  },

  getBookChapterDataFun(link, number) {
    this.setData({
      chapterArr: ""
    }) // 先清空数据，让菊花图显示出来
    return this.getBookChapterData(link, number).then(res => {
      this.stopEvent(res)

      this.setData({
        chapterArr: res
      })
    }).catch(err => {
      console.log(err)
    })
  },

  stopEvent(res) {
    if (res.order <= 1) {
      this.setData({
        prevChapterColor: "#333"
      })
    } else {
      this.setData({
        prevChapterColor: "#fff"
      })
    }

    if (res.order >= this.data.chapterListData.chapters.length) {
      this.setData({
        nextChapterColor: "#333"
      })
    } else {
      this.setData({
        nextChapterColor: "#fff"
      })
    }
  },


  toggleTextSize(e) { // 改变字体的大小
    this.setData({
      chapterSize: e.detail.value
    })
  },

  addBigText() {
    if (this.data.chapterSize >= 40) {
      return
    } else {
      let size = this.data.chapterSize + 2;
      this.setData({
        chapterSize: size
      })
    }
  }, // 增大字体

  addSmallText() {
    if (this.data.chapterSize <= 20) {
      return
    } else {
      let size = this.data.chapterSize - 2;
      this.setData({
        chapterSize: size
      })
    }
  }, // 减小字体


  // --- 左滑事件

  addPageData(e) {
    this.setData({
      xNum: e.touches[0].pageX
    })
  },

  addPageMove(e) {
    if (e.touches[0].pageX > this.data.xNum) {
      if (parseInt(this.data.chapterListWidth) === 0) {
        return
      } else {
        let jl = e.touches[0].pageX - this.data.xNum
        if (jl >= 160) {
          jl = 160
        }
        this.setData({
          chapterListWidth: `${jl / 2 - 80}%`
        })
      }
    } else {
      if (parseInt(this.data.chapterListWidth) === -80) {
        return
      } else {
        let jl = this.data.xNum - e.touches[0].pageX
        if (jl >= 160) {
          jl = 160
        }
        this.setData({
          chapterListWidth: `${- jl/ 2}%`
        })
      }
    }

  },

  addPageEnd(e) {
    if (parseInt(this.data.chapterListWidth) < -40) {
      this.setData({
        chapterListWidth: "-80%"
      })
    } else {
      this.setData({
        chapterListWidth: 0
      })
    }
  },


  // 章节样式切换
  taggoleStyle() {
    let number = wx.getStorageSync("styleNumber")
    number++
    if (number > 4) {
      number = 1
    }

    this.setData({
      textColor: this.data.textStyle[number - 1].textColor,
      textBgcolor: this.data.textStyle[number - 1].textBgcolor
    })

    wx.setStorage({
      key: 'styleNumber',
      data: number
    })
  },

  toggleLy() {
    wx.navigateTo({
      url: `/pages/bookIntro/intro-start/index?id=${this.data.chapterListData.book}`
    })
  },

  goFirstPage() {
    wx.navigateTo({
      url: '/pages/bookEnter/search/index'
    })
  }
})